<?php

namespace app\admin\controller;

use think\facade\Db;
use think\paginate;
use think\facade\Request;
use app\common\model\Withdraw as WithdrawModel;
use app\common\model\User;
use think\facade\View;

class Withdraw extends Base
{
    //提现列表
    public function index(Request $request)
    {
        $keyword = trim(input('get.keyword'));
        $type = trim(input('get.type'));
        $status = trim(input('get.status'));
        $start_time = trim(input('get.start_time'));
        $end_time = trim(input('get.end_time'));

        if (!empty($type)) {
            $whe[] = ['type', '=', $type];
        }
        if (!empty($status)) {
            $whe[] = ['status', '=', $status];
        }

        if (!empty($end_time)) {
            $end_time = strtotime($end_time) + 86399;
        } else {
            $end_time = time();
        }
        if (!empty($start_time)) {
            $start_time = strtotime($start_time);
            if ($start_time > $end_time) {
                $this->error('开始时间不能大于结束时间');
            }
            $whe[] = ['addtime', 'BETWEEN', array($start_time, $end_time)];
        } else {
            $whe[] = ['addtime', '<', $end_time];
        }

        $data = WithdrawModel::getList($whe, '*', "id desc");
        foreach ($data['list'] as $key => $val) {
            $name = DB::name("user")->where(['id' => $val['user_id']])->value("nickname");
            $data['list'][$key]['user_name'] = $name;
            $data['list'][$key]['imgurl'] = imageUrl($val['imgurl']);
        }

        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        View::assign('list', $data['list']);
        return View::fetch('Withdraw/index');
    }

    //审核
    public function pass()
    {
        $request = Request::instance();
        $status = $request->param('status');
        $id = $request->param('id');
        $res = Db::name('withdraw')->where(['id' => $id])->find();
        if (empty($res)) {
            return $this->err("参数错误");
        }
        if ($status == 1) {  //通过
            if ($res['type'] == 1) {
//                return $this->wx($res['tal_money'],$res['user_id'],$id);
            }
            $data['id'] = $id;
            $data['status'] = 2;
            $data['end_time'] = time();
            $dd = Db::name('withdraw')->where(['id' => $id])->update($data);
            if ($dd) {

                return $this->succ("审核成功");
            } else {
                return $this->err("网络故障，请稍后重试");
            }
        } elseif ($status == 2) { //拒绝
            $data['id'] = $id;
            $data['status'] = 3;
            $data['reason'] = $request->param('reason');
            $data['end_time'] = time();
            $dd = Db::name('withdraw')->where(['id' => $id])->update($data);
            if ($dd) {
                User::changeMoney2($res['user_id'], $res['tal_money'], 6, '提现驳回');
                User::changeMoney2($res['user_id'], $res['sxf'], 6, '提现驳回手续费');
                return $this->renderSuccess("审核成功");
            } else {
                return $this->renderError("网络故障，请稍后重试");
            }
        }
    }

    //微信提现
    public function wx($amount, $user_id, $order_num)
    {
        $openid = DB::name("user")->where(array("id" => $user_id))->value("openid");
        //付款
        header('Content-Type: text/xml');
        //微信付款到个人的接口
        $amount = $amount * 100;
        $str = $this->createNonceStr(32);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $params["mch_appid"] = config("wxpay")['appid'];   //小程序appid
        $params["mchid"] = config("wxpay")['mch_id'];   //商户号 微信支付平台账号
        $params["nonce_str"] = $str;   //随机字符串
        $params["partner_trade_no"] = $order_num;      //商户订单号
        $params["amount"] = $amount;          //金额
        $params["desc"] = '商户提现';//企业付款描述
        $params["openid"] = $openid;          //用户openid
        $params["check_name"] = 'NO_CHECK';       //不检验用户姓名
        $params['spbill_create_ip'] = '127.0.0.1';  //服务器IP

        //生成签名(签名算法后面详细介绍)
        $str = 'amount=' . $params["amount"] . '&check_name=' . $params["check_name"] . '&desc=' . $params["desc"] . '&mch_appid=' . $params["mch_appid"] . '&mchid=' . $params["mchid"] . '&nonce_str=' . $params["nonce_str"] . '&openid=' . $params["openid"] . '&partner_trade_no=' . $params["partner_trade_no"] . '&spbill_create_ip=' . $params['spbill_create_ip'] . '&key=' . config('wxpay')['key'];
        //md5加密 转换成大写
        $sign = strtoupper(md5($str));
        $params["sign"] = $sign;//签名
        $xml = $this->arrayToXml($params);
        $result = $this->curl_post_ssl($url, $xml);
        $data = $this->xml_to_array($result);
        if ($data['result_code'] == "SUCCESS") {
            $dd = DB::name("withdraw")->where(array("id" => $order_num))->setField("status", 1);
        } else {
            $dd = 0;
        }
        if ($dd) {
            return $this->renderSuccess("审核成功");
        } else {
            return $this->renderError("通过失败");
        }

    }

    //xml 转换成数组

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //订单号

    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    //获取随机字符串

    /**
     *   作用：使用证书，以post方式提交xml到对应的接口url
     */
    public function curl_post_ssl($url, $vars, $second = 30)
    {
        $ch = curl_init();//超时时间curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //以下两种方式需选择一种
        /******* 此处必须为文件服务器根目录绝对路径 不可使用变量代替*********/
        curl_setopt($ch, CURLOPT_SSLCERT, ROOT_PATH . "/public/cert/apiclient_cert.pem");
        curl_setopt($ch, CURLOPT_SSLKEY, ROOT_PATH . "/public/cert/apiclient_key.pem");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    //数组转xml

    private function xml_to_array($xml)
    {
        //禁止引用外部 xml 实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }


    //使用证书，以post方式提交xml到对应的接口url

    public function ordernum($uid)
    {
        $order = "S" . date("ymdHis", time()) . sprintf("%04d", $uid) . rand(1111, 9999);
        return $order;
    }
}